﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
using System.Diagnostics;
using System.Reflection;

namespace DAL
{
    public class ReadWriteFile
    {
        public void readFile(string filePath, out CityObject[] citiesCoordinate, out int numOfCity)
        {
            StreamReader doc = new StreamReader(filePath);
            int maxIndex = 1;
            string line = "";
            string pattern = " ";
            Regex myRegex = new Regex(pattern);
            Regex rg = new Regex(@"\s+");
            while ((line = doc.ReadLine()) != null)
            {
                if (line.IndexOf("DIMENSION") != -1)
                {
                    maxIndex = Convert.ToInt32(line.Substring(line.LastIndexOf(" "), line.Length - line.LastIndexOf(" ")));
                    break;
                }
            }
            citiesCoordinate = new CityObject[maxIndex];
            numOfCity = maxIndex;
            while ((line = doc.ReadLine()) != null)
            {
                line = line.Trim();
                line = rg.Replace(line, " ");
                if (Char.IsNumber(line[0]))
                {
                    string[] temp = myRegex.Split(line);
                    int index = Convert.ToInt32(temp[0]);
                    citiesCoordinate[index - 1] = new CityObject(Convert.ToInt32(temp[1]), Convert.ToInt32(temp[2]));
                }
            }
            doc.Dispose();
            doc.Close();        
        }

        public void writeTourToFile(string fileName, string seed, int[] tour, int numOfCity, double fitness, Stopwatch time)
        {
            StreamWriter wr = new StreamWriter(fileName);
            wr.WriteLine("fileName: " + fileName);    
            wr.WriteLine("Seed: " + seed);         
            wr.WriteLine("Fitness: " + fitness);           
            for (int i = 0; i < numOfCity; i++)
            {
                wr.Write(tour[i] + "\t");
            }
            wr.WriteLine();          
            wr.WriteLine("Time: " + time.Elapsed.ToString());
            wr.Close();
        }
              
        public void writeBestFitnessInPop(string fileName, List<PathTour> currentPop, double totalFitness, int repeatStt, PathTour bestChromosome)
            {
                StreamWriter wr = new StreamWriter(fileName, true);
                try
                {
                    wr.WriteLine(bestChromosome.Fitness + "\t" + totalFitness);
                }
                catch (System.Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    wr.Flush();
                    wr.Close();
                }
            }             
        
    }
}
